package com.tuniondata.netty.bean;

import com.tuniondata.netty.common.Pack;
import com.tuniondata.netty.common.Unpack;
import com.tuniondata.netty.common.protocol.Protocol;
import io.swagger.annotations.ApiModelProperty;

/**
 * @author yuxinchao
 */
@ApiBinaryDTO(mtp = "4008")
public class ResponseDTO implements ApiBinaryBean {

    public static final ResponseDTO OK = new ResponseDTO("00") {
        @Override
        public void setCode(String code) {
            throw new IllegalStateException("ImmutableBean");
        }

        @Override
        public void setMessage(String message) {
            throw new IllegalStateException("ImmutableBean");
        }
    };

    @ApiModelProperty(value = "应答码", required = true)
    private String code;

    @ApiModelProperty(value = "应答消息")
    private String message;

    public ResponseDTO() {
    }

    public ResponseDTO(String code) {
        this.code = code;
        this.message = ResponseCodeConstant.getMessage(code, "unknown error code");
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @SuppressWarnings({"unchecked"})
    public <T> T code(String code) {
        this.setCode(code);
        return (T) this;
    }

    @SuppressWarnings({"unchecked"})
    public <T> T codeAndMessage(String code, String message) {
        this.setCode(code);
        this.setMessage(message);
        return (T) this;
    }

    @Override
    public byte[] pack() throws Exception {
        Pack pack = Pack.alloc();
        return pack.add(code).pack();
    }

    @Override
    public void unpack(byte[] data) throws Exception {
        Unpack unpack = Unpack.alloc(data);
        this.code = unpack.string(2);
    }
}
